package cn.sjxy.doctorms.controller;

import cn.sjxy.doctorms.domain.Result;
import cn.sjxy.doctorms.domain.User;
import cn.sjxy.doctorms.service.UserService;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated// 使用Validated注解，启用参数校验功能，对应下面的@Pattern注解
public class UserController {
    @Autowired
    private UserService userService;
    //用户登录
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{3,16}$") String username, @Pattern(regexp = "^\\S{6,16}$") String password){
        User loginUser = userService.findByUsername(username);
        if(loginUser==null){
            return Result.error("用户名错误");
        }
        if(password.equals(loginUser.getPassword())){
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",loginUser.getUserId());
            claims.put("username",loginUser.getUsername());
            return Result.success();
        }
        return Result.error("密码错误");
    }
    //注册用户
    @PostMapping("/register")// \\S{6,16}表示五到十六位非空字符
    public Result register(@Pattern(regexp = "^\\S{1,16}$") String username,@Pattern(regexp = "^\\S{6,16}$") String password){
        User u = userService.findByUsername(username);
        if(u==null){
            userService.register(username,password);
            return Result.success();
        }
        else{
            return Result.error("用户名已存在");
        }
    }
}
